<?php

/**
 * [PHPFOX_HEADER]
 */
defined('PHPFOX') or exit('NO DICE!');

/**
 * 
 * 
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Raymond Benc
 * @package 		Phpfox_Service
 * @version 		$Id: process.class.php 2738 2011-07-15 10:28:44Z Miguel_Espinoza $
 */
class Recordvideo_Service_Process extends Phpfox_Service {

    /**
     * Class constructor
     */
    public function __construct() {
        
    }

    public function downloadVideo($sVideoUrl,$buildDir = TRUE, $bCdn = TRUE) {
        $sBaseDestination = $sDestination = Phpfox::getParam('video.dir');
        
        //file name
        $sFileName = md5(PHPFOX_TIME . uniqid()) . '.flv';
        
        //temp dir
//        $sTempDir = PHPFOX_DIR_CACHE . $sFileName;
        
        //build dir
        if($buildDir) {
            $sDestination = $this->buildDir($sDestination);
        }
        
        $sDestination .= $sFileName;
        
        //copy to dir video
        if(!@copy($sVideoUrl, $sDestination)) {
            return FALSE;
        }
        
        //if CDN
        if (Phpfox::getParam('core.allow_cdn') && $bCdn) {
            $bReturn = Phpfox::getLib('cdn')->put($sDestination);

            if ($bReturn === FALSE) {
                return FALSE;
            }
        }
        
        return str_replace('\\', '/', str_replace($sBaseDestination, '', $sDestination));
    }
    
    
    private function _getFileExtension($sFileName) {
    	$sFileName = strtolower($sFileName);
        $aExts = preg_split("/[\/\\.]/", $sFileName);
        $iCnt = count($aExts)-1;

        return strtolower($aExts[$iCnt]);
    }

    public function buildDir($sDestination) {
        $sBaseDestination = $sDestination;
        if (!PHPFOX_SAFE_MODE && Phpfox::getParam('core.build_file_dir') && !defined('PHPFOX_IS_HOSTED_SCRIPT')) {
            $aParts = explode('/', Phpfox::getParam('core.build_format'));

            foreach ($aParts as $sPart) {
                $sDate = date($sPart) . PHPFOX_DS;
                $sDestination .= $sDate;
                if (!is_dir($sDestination)) {
                    @mkdir($sDestination, 0777);
                    @chmod($sDestination, 0777);
                }
            }

            // Make sure the directory was actually created, if not we use the default dir we know is working
            if (is_dir($sDestination)) {
                return $sDestination;
            }
        }

        return $sBaseDestination;
    }

}

?>